package com.intellif.mozping.boot;

import com.alibaba.fastjson.JSONObject;
import com.intellif.mozping.StartInsert;
import com.intellif.mozping.dao.CarMapper;
import com.intellif.mozping.entity.Car;
import com.intellif.mozping.entityfactory.RandomObjFactory;
import com.intellif.mozping.util.SqlSessionFactoryUtil;
import org.apache.ibatis.session.SqlSession;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.ArrayList;
import java.util.Random;
import java.util.concurrent.Callable;

/**
 * @author by mozping
 * @Classname AddCarThread
 * @Description TODO
 * @Date 2019/6/22 11:18
 */
public class AddCarThread implements Callable<JSONObject> {

    private static final Logger LOG = LoggerFactory.getLogger(AddCarThread.class);
    private static final String CONFIG_FILE_PATH = "mybatis/postgresql-config.xml";


    private int total;
    private int batchNum;

    public AddCarThread(int total, int batchNum) {
        this.total = total;
        this.batchNum = batchNum;
    }

    @Override
    public JSONObject call() throws Exception {
        Thread.sleep(new Random().nextInt(100));
        JSONObject jsonObject = new JSONObject();
        int loop = total / batchNum;
        ArrayList<Car> list = new ArrayList<>(batchNum);
        SqlSession sqlSession = SqlSessionFactoryUtil.getSqlSessionFactoryInstaceByConfig(CONFIG_FILE_PATH).openSession();
        CarMapper carMapper = sqlSession.getMapper(CarMapper.class);
        //ѭ������
        long begin = System.currentTimeMillis();
        int numOfRecord = 0;
        LOG.info("�߳�" + Thread.currentThread().getName() + "��ʼִ��...");
        for (int j = 1; j <= loop; j++) {
            //1.������batchNum��car���󣬲����뵽list
            for (int i = 1; i <= batchNum ; i++) {
                list.add(RandomObjFactory.getRandomCar());
            }
            //2.�������ݿ�
            LOG.info("�߳�" + Thread.currentThread().getName() + "��ʼ����...");
            int rowAffected = carMapper.addCarBatch(list);
            LOG.info("�߳�" + Thread.currentThread().getName() + "����һ�����...");
            list.clear();
            numOfRecord += rowAffected;
            //��ʾ�ύ����
            //if (j % 10 == 0) {
                sqlSession.commit();
                System.out.println("�����ύһ��...");
            //}
        }
        sqlSession.commit();
        sqlSession.close();
        long time = System.currentTimeMillis() - begin;
        long speed = (numOfRecord * 1000) / time;

        jsonObject.put("Added", numOfRecord);
        jsonObject.put("Total", total);
        jsonObject.put("Error", total - numOfRecord);
        jsonObject.put("Time", time);
        jsonObject.put("Speed", speed + " /S;");

        StartInsert.latch.countDown();
        LOG.info("�߳�" + Thread.currentThread().getName() + "ִ�н����" + jsonObject);
        return jsonObject;
    }

}